<?php

namespace app\modules\Finance\models;

use Yii;
use app\modules\Order\models\Order;
use app\modules\Finance\models\FinanceCompany;
use dektrium\user\models\User;
use yii\db\Query;

/**
 * This is the model class for table "finance".
 *
 * @property integer $id
 * @property integer $type
 * @property integer $price_type
 * @property string $company
 * @property string $account
 * @property string $name
 * @property string $desc
 * @property string $img
 * @property integer $status
 * @property integer $user_id
 * @property string $created_at
 * @property string $updated_at
 */
class Finance extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'finance';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['type', 'price_type', 'status', 'user_id','is_invoice'], 'integer'],
            [['created_at', 'updated_at'], 'safe'],
            [['company', 'account', 'img'], 'string', 'max' => 128],
            [['receive_account'], 'string', 'max' => 64],
            [['name', 'code'], 'string', 'max' => 16],
            [['desc'], 'string', 'max' => 1024],
            [['remark'], 'string', 'max' => 1500],
        ];
    }


    // 保存前处理
    public function beforeSave($insert) {//{{{
        if($insert){
            $this->created_at = date("Y-m-d H:i:s");
            $this->user_id    = Yii::$app->user->id;

			$t = 'F';
			if($this->type == 2){
				
				$t = 'A';
			}elseif($this->type == 3){
				
				$t = 'R';
			}

			$d = date("Ymd");
			$count = Finance::find()->where(['>=', 'created_at', date("Y-m-d 00:00:00")])->count();

			$num = sprintf("%04d", $count+1);

            $this->code = sprintf("%s%s%s", $t, $d, $num);
        }
        return parent::beforeSave($insert);
    }//}}}


    // 保存后执行
	public function afterSave($insert, $changedAttributes){//{{{

		parent::afterSave($insert, $changedAttributes);

		if($insert) {
			// 判断收款单位是否存在 不存在新增一条
			if($this->company && $this->name ) {
				$ret = FinanceCompany::find()->where(['company'=>$this->company, 'account'=>$this->account, 'name'=>$this->name])->one();

				if(empty($ret)){
					$model = new FinanceCompany();
					$model->name  = $this->name;
					$model->account = $this->account;
					$model->company = $this->company;

					$model->save();
				}
			}

			// 日志
			$desc = sprintf("创建收款单  单号 %s", $this->code);
			Yii::$app->logs->info($this->id, 9, $desc);
		}
	}//}}}



    //  获取关联的发票单
    public function getInvoice(){
        
        return $this->hasMany(Invoice::className(), ['finance_id' => 'id']);
    }

    //  获取关联的发票单总金额
    public function getInvoiceOrderPrice(){
        
        return $this->hasMany(InvoiceOrder::className(), ['finance_id' => 'id'])->sum('price');
    }

	//  获取关联的订单
	public function getOrder(){
		
        return $this->hasMany(FinanceOrder::className(), ['finance_id' => 'id']); //->all()
	}

	//  获取关联的订单总金额
	public function getOrderPrice(){
        $model = $this->hasMany(FinanceOrder::className(), ['finance_id' => 'id'])->sum('price');
		return $model;
	}

	// 获取审批关联的所有发票　合同文件
    public function getAllImg(){
        return $this->hasMany(FinanceImg::className(), ['finance_id' => 'id']);
    }

    //  获取审批负责销售信息
    public function getUser(){
		return $this->hasOne(User::className(), ['id' => 'user_id']);
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'type' => Yii::t('app', 'Type'),
            'price_type' => Yii::t('app.finance', 'Price Type'),
            'company' => Yii::t('app.finance', 'Company'),
            'account' => Yii::t('app.finance', 'Account'),
            'name' => Yii::t('app.finance', 'Name'),
            'desc' => Yii::t('app.finance', 'Desc'),
            'img' => Yii::t('app.finance', 'Img'),
            'status' => Yii::t('app', 'Status'),
            'user_id' => Yii::t('app', '提交人'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
            'code' => Yii::t('app', '单号'),
            'is_invoice' => Yii::t('app', '开发票'),
            'receive_account' => Yii::t('app.finance', 'Receive Account'),
            'remark' => Yii::t('app.finance', 'Remark'),
            'price' => Yii::t('app.finance', '金额'),
        ];
    }
}
